import { Injectable } from '@angular/core';
import { CanActivate, Router ,RouterStateSnapshot, ActivatedRouteSnapshot} from '@angular/router';
import { Store, select} from '@ngrx/store';
import {map, defaultIfEmpty} from 'rxjs/operators';
import * as fromRoot from '../reducers';
import {getAuthState} from '../reducers';
import { Observable } from 'rxjs';

@Injectable({
    providedIn: 'root'
})
export class AuthGuard implements CanActivate{
    constructor(
        private $store: Store<fromRoot.State>,
        private router: Router
        ) {

    }
    canActivate(route:ActivatedRouteSnapshot,state:RouterStateSnapshot): Observable <boolean> {
       return this.$store.pipe(
           select(getAuthState),
           map(auth=>{
               const result = auth.token !== null&&auth.token!==undefined;
               if(!result){
                   this.router.navigate(['login']);
               }
               return result
           }),
           defaultIfEmpty(false)
         )
    }
}